package org.cheniy.domain.strategy.service.rule.tree.impl;

import lombok.extern.slf4j.Slf4j;
import org.cheniy.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import org.cheniy.domain.strategy.repository.IStrategyRepository;
import org.cheniy.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.cheniy.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author cheniy
 * @description 抽奖次数限定树过滤节点
 * @create 2025/3/8 15:32
 */

@Slf4j
@Component("rule_lock")
public class RuleLockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyRepository iStrategyRepository;



    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-次数锁 userId:{} strategyId:{} awardId:{} ruleValue:{}",userId, strategyId, awardId,ruleValue);

        long raffleCount=0L;

       try {
           raffleCount = Long.parseLong(ruleValue);
       }catch (Exception e){
           throw new RuntimeException("规则过滤-次数锁异常ruleValue:"+ruleValue+"配置不正确");
       }
        // 查询用户抽奖次数 - 当天的；策略ID:活动ID 1:1 的配置，可以直接用 strategyId 查询。
        Integer userRaffleCount = iStrategyRepository.queryTodayUserRaffleCount(userId, strategyId);

        // 符合抽奖次数则放行，否则拦截
       if (userRaffleCount>=raffleCount){
           log.info("规则过滤-次数锁【放行】 userId:{} strategyId:{} awardId:{} raffleCount:{} userRaffleCount:{}", userId, strategyId, awardId, userRaffleCount, userRaffleCount);
           return DefaultTreeFactory.TreeActionEntity.builder()
                   .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                   .build();
       }
        log.info("规则过滤-次数锁【拦截】 userId:{} strategyId:{} awardId:{} raffleCount:{} userRaffleCount:{}", userId, strategyId, awardId, userRaffleCount, userRaffleCount);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .build();
    }
}
